package com.aaa.forum.controller;

import com.aaa.forum.common.AppResult;
import com.aaa.forum.common.ResultCode;
import com.aaa.forum.config.AppConfig;
import com.aaa.forum.exception.ApplicationException;
import com.aaa.forum.model.Article;
import com.aaa.forum.model.ArticleReply;
import com.aaa.forum.model.User;
import com.aaa.forum.services.IArticleReplyService;
import com.aaa.forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "回复接口")
@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {

    @Resource
    private IArticleService articleService;

    @Resource
    private IArticleReplyService articleReplyService;

    @ApiOperation("回复帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("articleId") Long articleId,
                            @ApiParam("回复内容") @RequestParam("content") String content) {
        // 1. 校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 2. 校验帖子状态
        Article article = articleService.selectById(articleId);
        if (article == null || article.getDeleteState() == 1) {
            // 帖子不存在 或 已删除
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1) {
            // 帖子封贴状态
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }
        // 3. 调用 service
        ArticleReply articleReply = new ArticleReply();
        articleReply.setUserId(user.getId());
        articleReply.setArticleId(articleId);
        articleReply.setContent(content);
        articleReplyService.create(articleReply);

        return AppResult.success("回复成功");
    }

    @ApiOperation("获取回复列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(@ApiParam("帖子id") @RequestParam("articleId") Long articleId) {
        // 查询并返回结果
        List<ArticleReply> result = articleReplyService.selectAllByArticleId(articleId);
        return AppResult.success(result);
    }
}
